import React, { useState, useEffect } from 'react';
import { Input, Button, Checkbox } from 'antd';
import { UserOutlined, LockOutlined, SafetyCertificateOutlined } from '@ant-design/icons';

interface LoginFormData {
  username: string;
  password: string;
  captcha: string;
  remember: boolean;
}

interface LoginFormProps {
  onSubmit: (values: LoginFormData) => Promise<void>;
  loading?: boolean;
}

const LoginForm: React.FC<LoginFormProps> = ({ onSubmit, loading = false }) => {
  const [formData, setFormData] = useState<LoginFormData>({
    username: '',
    password: '',
    captcha: '',
    remember: false,
  });
  const [errors, setErrors] = useState<Partial<LoginFormData>>({});
  const [captchaUrl, setCaptchaUrl] = useState<string>('');

  // 模拟验证码生成
  const generateCaptcha = () => {
    const canvas = document.createElement('canvas');
    canvas.width = 100;
    canvas.height = 40;
    const ctx = canvas.getContext('2d');
    
    if (ctx) {
      // 背景
      ctx.fillStyle = '#f8f9fa';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      
      // 随机干扰线
      for (let i = 0; i < 5; i++) {
        ctx.strokeStyle = '#e1e8ed';
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.stroke();
      }
      
      // 验证码文字
      const code = Math.random().toString(36).substring(2, 6).toUpperCase();
      ctx.font = 'bold 24px Arial';
      ctx.fillStyle = '#2c3e50';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      
      // 随机旋转每个字符
      for (let i = 0; i < code.length; i++) {
        ctx.save();
        ctx.translate(20 + i * 20, 20);
        ctx.rotate((Math.random() - 0.5) * 0.4);
        ctx.fillText(code[i], 0, 0);
        ctx.restore();
      }
      
      setCaptchaUrl(canvas.toDataURL());
    }
  };

  useEffect(() => {
    generateCaptcha();
  }, []);

  const validateForm = (): boolean => {
    const newErrors: Partial<LoginFormData> = {};

    if (!formData.username.trim()) {
      newErrors.username = '请输入用户名';
    }

    if (!formData.password) {
      newErrors.password = '请输入密码';
    } else if (formData.password.length < 6) {
      newErrors.password = '密码长度至少6位';
    }

    if (!formData.captcha.trim()) {
      newErrors.captcha = '请输入验证码';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleInputChange = (field: keyof LoginFormData, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // 清除对应字段的错误
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: undefined }));
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      return;
    }

    try {
      await onSubmit(formData);
    } catch (error) {
      // 登录失败时刷新验证码
      generateCaptcha();
      setFormData(prev => ({ ...prev, captcha: '' }));
    }
  };

  const handleCaptchaClick = () => {
    generateCaptcha();
  };

  return (
    <form onSubmit={handleSubmit} className="login-form">
      <div className="form-group">
        <label className="form-label">用户名</label>
        <div className="input-wrapper">
          <Input
            size="large"
            prefix={<UserOutlined className="input-icon" />}
            placeholder="请输入用户名"
            value={formData.username}
            onChange={(e) => handleInputChange('username', e.target.value)}
            className={errors.username ? 'form-input input-with-icon error' : 'form-input input-with-icon'}
            disabled={loading}
          />
        </div>
        {errors.username && <div className="form-error">{errors.username}</div>}
      </div>

      <div className="form-group">
        <label className="form-label">密码</label>
        <div className="input-wrapper">
          <Input.Password
            size="large"
            prefix={<LockOutlined className="input-icon" />}
            placeholder="请输入密码"
            value={formData.password}
            onChange={(e) => handleInputChange('password', e.target.value)}
            className={errors.password ? 'form-input input-with-icon error' : 'form-input input-with-icon'}
            disabled={loading}
          />
        </div>
        {errors.password && <div className="form-error">{errors.password}</div>}
      </div>

      <div className="form-group">
        <label className="form-label">验证码</label>
        <div className="captcha-container">
          <div className="captcha-input">
            <div className="input-wrapper">
              <Input
                size="large"
                prefix={<SafetyCertificateOutlined className="input-icon" />}
                placeholder="请输入验证码"
                value={formData.captcha}
                onChange={(e) => handleInputChange('captcha', e.target.value)}
                className={errors.captcha ? 'form-input input-with-icon error' : 'form-input input-with-icon'}
                disabled={loading}
              />
            </div>
          </div>
          <div 
            className="captcha-image" 
            onClick={handleCaptchaClick}
            title="点击刷新验证码"
          >
            {captchaUrl ? (
              <img 
                src={captchaUrl} 
                alt="验证码" 
                style={{ width: '100%', height: '100%', borderRadius: '6px' }}
              />
            ) : (
              '点击获取'
            )}
          </div>
        </div>
        {errors.captcha && <div className="form-error">{errors.captcha}</div>}
      </div>

      <div className="remember-forgot">
        <Checkbox
          checked={formData.remember}
          onChange={(e) => handleInputChange('remember', e.target.checked)}
          disabled={loading}
        >
          记住我
        </Checkbox>
        <a href="/forgot-password" className="forgot-password">忘记密码？</a>
      </div>

      <Button
        type="primary"
        htmlType="submit"
        className="login-button"
        loading={loading}
        disabled={loading}
      >
        {loading ? '登录中...' : '登录'}
      </Button>
    </form>
  );
};

export default LoginForm;